package com.koolearn.lms.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by hanchao on 2016/9/6.
 */
public class ExcelWriter {
    public static final int VERSION_2003 = 1;
    public static final int VERSION_2010 = 2;

    public static void write(File file, List<Map<String, Object>> datas) {
        write(file, datas, null, VERSION_2003);
    }

    public static void write(File file, List<Map<String, Object>> datas, String sheetName) {
        write(file, datas, sheetName, VERSION_2003);
    }

    public static void write(File file, List<Map<String, Object>> datas, String sheetName, int version) {
        if (CollectionUtils.isEmpty(datas)) {
            throw new IllegalArgumentException("dtas cant be null or empty!");
        }
        Workbook wb = null;
        if (version == VERSION_2003) {
            wb = new HSSFWorkbook();
        } else {
            wb = new XSSFWorkbook();
        }
        Sheet sheet = null;
        if (sheetName != null) {
            sheet = wb.createSheet(sheetName);
        } else {
            sheet = wb.createSheet();
        }
        sheet.setDefaultColumnWidth(4000);

        Row title = sheet.createRow(0);
        Collection columns = datas.get(0).keySet();

        int i = 0;
        for (Iterator<String> it = columns.iterator(); it.hasNext(); ) {
            title.createCell(i++).setCellValue(it.next());
        }

        int rowIndex = 1;
        for (Map<String, Object> data : datas) {
            Row row = sheet.createRow(rowIndex++);
            Collection<Object> values = data.values();
            int cellIndex = 0;
            for (Object obj : values) {
                String column = String.valueOf(obj);
                row.createCell(cellIndex++).setCellValue(column);
            }
        }
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
